package handler

import (
	"article-sys/cache"
	"article-sys/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	redis_key := "article_id_" + strconv.Itoa(int(data.ID))
	model.DB.Create(&data)
	jsonData, _ := json.Marshal(&data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	var data []model.Article
	if err := model.DB.
		Find(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": data,
	})
	return
}
func Delete(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	if err := model.DB.Where("id = ?", id).Delete(&model.Article{}); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "article_id_" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.PostForm(c.DefaultQuery("page", "1")))
	size, _ := strconv.Atoi(c.PostForm(c.DefaultQuery("size", "2")))
	offset := (page - 1) * size
	var data []model.Article
	redis_key := "article_page_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Table("articles").
			Select("articles.title",
				"articles.content",
				"articles.author").
			Limit(size).
			Offset(offset).
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}

	var total int64
	model.DB.Table("articles").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"total": total,
	})
}
